import { Component } from "react";
import Taro from "@tarojs/taro";
import { ActionSheet, SafeArea, ConfigProvider } from "@taroify/core"
import { View, Text, Image } from "@tarojs/components";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import { GButton } from "@/components/GButton";
import languageModel from "@/models/language";
import IconInput from "@/components/IconInput";
import CountryPicker, { defaultCountryCode } from '@/components/CountryPicker';
import userStateModel, { UserState_Store_Key } from "@/models/userState";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import ListItem from "@/components/ListItem";
import Avatar from '@/components/Avatar';
import { norInject, INorInjectProps } from "@/models";
import PageContainer from "@/components/PageContainer";
import Toast from "@/utils/Toast";
import logout from "@/utils/logout";
import { destructionAccount } from '@/services/account';
import { getMobileCode } from '@/services/aepApi';
import regular from '@/utils/regular';

interface IProps extends INorInjectProps {

}

const dstyle = GStyleSheet.create({
  page: {
    backgroundColor: DynamicColors.normalBackgroundColor
  },
  container: {
    display: 'flex',
    height: '100%',
    flexDirection: 'column',
  },
  content: {
    flex: 1,
    paddingLeft: '10%',
    paddingRight: '10%',
    marginTop: 20,
  },
  sendButton: {
    backgroundColor: '#F5F5F5',
    borderRadius: 20,
    padding: 5,
    paddingLeft: 15,
    paddingRight: 15,
  },
  sendButtonText: {
    color: DynamicColors.normalTextColor
  }
});

@norInject(UserState_Store_Key)
@observer
class BindPhone extends Component<IProps> {

  timer: any

  state = {
    phoneCode: languageModel.phoneCode ?? defaultCountryCode,
    phone: '',
    code: '',
    count: 0,
  }


  startCountDown = () => {
    this.endCountDown();
    this.timer = setInterval(() => {
      const { count } = this.state;
      const newCount = count - 1;
      if (newCount <= 0) {
        this.endCountDown();
      }
      this.setState({ count: newCount });
    }, 1000)
    this.setState({ count: 60 });
  }

  endCountDown = () => {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  sendCode = async () => {
    const { phoneCode, phone } = this.state;
    // 检查手机是否合法
    if (regular.phone.test(phone)) {
      Toast.loading('')
      const res = await getMobileCode({ mobile: `${phoneCode}${phone}`, type: 2 });
      Toast.hideLoading()
      if (res.success) {
        Toast.success(i18n.t('SEND_CODE_SUCCESS'))
        this.startCountDown();
      } else {
        Toast.error(res.message ?? i18n.t('SEND_CODE_FAIL'))
      }
    } else {
      Toast.error(i18n.t('PHONE_NOT_RIGHT'))
    }
  }

  onConfirm = async () => {
    const { phoneCode, phone, code } = this.state;
    if (!regular.phone.test(phone)) {
      Toast.error(i18n.t('PHONE_NOT_RIGHT'))
      return
    }
    if (!code || code.length < 1) {
      Toast.error(i18n.t('PLE_INPUT_CODE'))
      return
    }
    Toast.loading('')
    const res = await userStateModel.updateUserInfo({ mobile: `${phoneCode}${phone}`, code });
    Toast.hideLoading()
    if (res.success) {
      Toast.success(i18n.t('REPLACE_THE_PHONE_NUMBER_SUCCESSFULLY'))
      Taro.navigateBack();
    } else {
      const { message, code: resCode } = res;
      switch (Number(resCode)) {
        case 9018:
          Toast.error(i18n.t('THE_PHONE_NUMBER_HAS_BEEN_REGISTERED'));
          break;
        case 9010:
          Toast.error(i18n.t('AUTH_CODE_ERROR'));
          break;
        case 1000024:
          Toast.error(i18n.t('AUTH_CODE_ERROR'));
          break;
        case 1000019:
          Toast.error(i18n.t('PHONE_ALREADY_TIED'));
          break;
        // case 1000030:
        //   Toast.error(i18n.t('MAILBOX_ALREADY_TIED'));
        //   break;
        default:
          Toast.error(message ?? i18n.t('REPLACE_THE_PHONE_NUMBER_FAILURE'));
          break;
      }
    }
  };

  changePhone = (e) => {
    this.setState({ phone: e.detail.value })
  }
  changeCode = (e) => {
    this.setState({ code: e.detail.value })
  }

  render() {
    const styles = dstyle.style;
    const { userState } = this.props;
    const { phoneCode, phone, code, count } = this.state;
    const canSend = count === 0;
    return (
      <PageContainer title={i18n.t('BIND_PHONE')} style={styles.page}>
        <View style={styles.container}>
          <View style={styles.content}>
            <CountryPicker />
            <IconInput
              value={phone}
              placeholder={i18n.t('PLE_INPUT_PHONE')}
              onInput={this.changePhone}
            />
            <IconInput
              value={code}
              placeholder={i18n.t('PLE_INPUT_CODE')}
              onInput={this.changeCode}
              extra={<View style={styles.sendButton} onClick={canSend ? this.sendCode : () => { }}>
                <Text style={styles.sendButtonText}>{canSend ? i18n.t('SEND') : `${count}s`}</Text>
              </View>}
            />
          </View>
          <View style={{ marginTop: 30, marginBottom: 30, height: 80, width: '100%' }}>
            <GButton
              text={i18n.t("CONFIRM")}
              onPress={this.onConfirm}
            />
          </View>
        </View>

      </PageContainer>
    );
  }
}

export default BindPhone;
